/*
 *  Netzpult - Your desk on the web
 *  Copyright (C) 2011  Ulrich Hilger, http://uhilger.de
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/
 */

package de.uhilger.netzpult.server;

import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.uhilger.netzpult.server.db.DataStorage;

/**
 * 
 * @author Copyright (c) Ulrich Hilger, http://uhilger.de
 * @author Published under the terms and conditions of
 * the <a href="http://www.gnu.org/licenses/" target="_blank">GNU General Public License</a>
 */
public class ContentServlet extends AbstractWebfilesServlet {

	public static final String DRAFT = "draft";
	public static final String NO = "no";
	public static final String YES = "yes";
	
	private static final long serialVersionUID = -6542394833577579531L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
			//test(req, resp);
			production(req, resp);
	}
	
	private void production(HttpServletRequest req, HttpServletResponse resp) {
		try {
			serveDocument(req, resp, req.getParameter("id"));
		} catch (Exception e) {
			try {
				serveDocument(req, resp, req.getPathInfo().split("/")[1]);
			} catch(Exception ex) {
				try {
					serveDocument(req, resp, req.getPathInfo().split("/")[2]);
				} catch(Exception ex2) {
					try {
						serveDocument(req, resp, req.getPathInfo().split("/")[3]);
					} catch(Exception ex3) {
						try {
							serveDocument(req, resp, req.getPathInfo().split("/")[4]);
						} catch(Exception ex4) {
							DocumentServer.logError(e);
						}
					}
				}
			}
		}
	}
	
	private void serveDocument(HttpServletRequest req, HttpServletResponse resp, String idStr) throws SQLException, IOException, Exception {
		int id = Integer.parseInt(idStr);
		boolean isPublic = ds.isPublic(id);
		String pathInfo = req.getPathInfo();
		String[] elements = pathInfo.split("/");
		int depth = elements.length;
		if(pathInfo.contains("/Netzpult")) {
			depth -= 1;
		}
		for(int i=0; i < depth; i++) {
			Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).finest("elements[" + i +"]=" + elements[i]);
		}
		String userNamePart = null;
		if(depth == 3) {
			userNamePart = elements[1]; 
			if(!isPublic && (userName == null || !userName.equals(userNamePart))) {
				userNamePart = "";
			}
		} else {
			userNamePart = userName;
		}
		/*if(userNamePart == null || userNamePart.length() < 1 || userNamePart.equals(AbstractWebfilesServlet.ANONYMOUS_OWNER)) {
			userNamePart = ds.getDocumentOwner(id);
		}*/
		boolean draftStatus = DataStorage.WITHOUT_DRAFT;
		String draft = req.getParameter(DRAFT);
		if(draft != null && draft.equalsIgnoreCase(YES)) {
			draftStatus = DataStorage.WITH_DRAFT;
		}
		Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).finest("userNamePart: " + userNamePart);
		DocumentServer.serveDocument(req, resp, ds, id, depth, userNamePart, isPublic, draftStatus);
	}
	
	private void test(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		Writer w = resp.getWriter();
		w.write("<html>");
		w.write("<head><title>netzpult</title></head>");
		w.write("<body>");

		String pathInfo = req.getPathInfo();

		w.write("<p>");
		w.write("request.getPathInfo = ");
		w.write(pathInfo);
		w.write("</p>");

		w.write("<p>Path elements:<br>");
		String[] pathElements = pathInfo.split("/");
		for (int i = 0; i < pathElements.length; i++) {
			w.write(pathElements[i]);
			w.write("<br>");
		}
		w.write("</p>");

		w.write("<p>");
		w.write("pathElements.length = ");
		w.write(Integer.toString(pathElements.length));
		w.write("</p>");

		w.write("</body");
		w.write("</html>");
		w.flush();
		w.close();
	}


}

